﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Net.Mail;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// Summary description for Myfunction
/// </summary>
public static class Myfunction
{
     
  #region Thao tac file
  public static string CopyFile(HttpPostedFile file,string folder,string name)
  {
    string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
    fileName += Path.GetExtension(file.FileName);

    file.SaveAs(MyConfig.serverPath +folder +"/" + fileName);
    return fileName;
  }

  public static string UpdateFile(HttpPostedFile file, string folder, string currentFile, string name)
  {
    File.Delete(MyConfig.serverPath + folder + "/" + currentFile);

    string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
    fileName += Path.GetExtension(file.FileName);

    file.SaveAs(MyConfig.serverPath + folder + "/" + fileName);
    return fileName;
  }

  public static string CopyFileThumbnail(HttpPostedFile file, string folder, string name)
  {
      string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");        
    fileName += Path.GetExtension(file.FileName);
    string newName = fileName.Replace(".", "_thumb.");

    file.SaveAs(MyConfig.serverPath + folder + "/" + newName);
    return newName;
  }

  public static string UpdateFileThumbnail(HttpPostedFile file, string folder, string currentFile,string name)
  {
    File.Delete(MyConfig.serverPath + folder + "/" + currentFile);

    string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");  
    fileName += Path.GetExtension(file.FileName);
    string newName = fileName.Replace(".", "_thumb.");

    file.SaveAs(MyConfig.serverPath + folder + "/" + newName);
    return newName;
  }


  public static void DeleteFile(string folder, string fileName)
  {
    if (File.Exists(MyConfig.serverPath + folder + "/" + fileName))
      File.Delete(MyConfig.serverPath + folder + "/" + fileName);
  }
  #endregion

  //Loc dau tieng viet
  private static readonly string[] VietNamChar = new string[] 
    { 
        "aeouidy", 
        "áàạảãâấầậẩẫăắằặẳẵ", 
        "éèẹẻẽêếềệểễ", 
        "óòọỏõôốồộổỗơớờợởỡ", 
        "úùụủũưứừựửữ", 
        "íìịỉĩ", 
        "đ", 
        "ýỳỵỷỹ", 
    };
  public static string LocDau(string str)
  {
    //Thay thế và lọc dấu từng char      
    for (int i = 1; i < VietNamChar.Length; i++)
    {
      for (int j = 0; j < VietNamChar[i].Length; j++)
        str = str.Replace(VietNamChar[i][j], VietNamChar[0][i - 1]);
    }
    return str;
  }

  //Xoa the HTML
  public static string RemoveHTMLTags(string source)
  {

    string expn = "<.*?>";

    return System.Text.RegularExpressions.Regex.Replace(source, expn, string.Empty);
  }
  
  //Kiem tra Email hop le
  public static bool isEmailValid(string strEmail)
  {
    string pattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
    Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
    if (!rx.IsMatch(strEmail))
    {
      return false;
    }
    return true;
  }

  //Ma hoa mat khau 
  public static string Encrypt(string strSource)
  {
    System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] bs = System.Text.Encoding.UTF8.GetBytes(strSource);
    bs = x.ComputeHash(bs);
    System.Text.StringBuilder s = new System.Text.StringBuilder();
    foreach (byte b in bs)
    {
      s.Append(b.ToString("x2").ToLower());
    }
    return s.ToString().ToUpper();
  }

  //Thong bao 

  public static void ThongBao(Literal literal, string strMesenge)
  {
    literal.Text = "<Script>alert('" + strMesenge + "')</Script>";
  }

  //Ham cat chuoi
  public static DateTime ReturnValidateDateTime(string s)
  {
      DateTime dt = new DateTime();
      DateTimeKind dtk = DateTimeKind.Local;
      try
      {
          DateTimeFormatInfo dtfi = new DateTimeFormatInfo();

          dtfi.ShortDatePattern = "dd/MM/yyyy hh:mm:ss tt";

          dtfi.DateSeparator = "/";

          dt = Convert.ToDateTime(s, dtfi);
      }
      catch
      {
      }
      return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dtk);
  }
  public static string SubString(string strInput, int countChar, string space)
  {
    string kq = "";
    string[] mang = strInput.Trim().Split(' ');
    if (mang.Length <= countChar)
    {
      kq = strInput.ToString();
    }
    else
    {
      for (int i = 0; i <= countChar; i++)
      {
        kq = kq + mang[i] + " ";

      }
      kq = kq + space;
    }

    return kq;
  }

  //Ham tao url friendly

  public static string toUrlFriendly(string strName)
  {
    string strTitle = strName.Trim();
    strTitle = strTitle.Trim('-');

    strTitle = strTitle.ToLower();
    char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
    strTitle = strTitle.Replace("c#", "C-Sharp");
    strTitle = strTitle.Replace("vb.net", "VB-Net");
    strTitle = strTitle.Replace("asp.net", "Asp-Net");

    //Loc dau tieng viet
    strTitle = LocDau(strTitle);

    //Thay dau (.) bang dau (-)
    strTitle.Replace(".", "-");

    //Thay ky tu dac biet bang dau (-)
    for (int i = 0; i < chars.Length; i++)
    {
      string strChar = chars.GetValue(i).ToString();
      if (strTitle.Contains(strChar))
      {
        strTitle = strTitle.Replace(strChar, string.Empty);
      }
    }
    //Thay the tat cac khoang trang bang 1 dau (-)
    strTitle = strTitle.Replace(" ", "-");

    //Thay the nhieu dau (-) bang 1 dau (-)
    strTitle = strTitle.Replace("--", "-");
    strTitle = strTitle.Replace("---", "-");
    strTitle = strTitle.Replace("----", "-");
    strTitle = strTitle.Replace("-----", "-");
    strTitle = strTitle.Replace("----", "-");
    strTitle = strTitle.Replace("---", "-");
    strTitle = strTitle.Replace("--", "-");

    //Trim Start and End Spaces
    strTitle = strTitle.Trim();

    //Trim "-" Hyphen 
    strTitle = strTitle.Trim('-');

    return strTitle;
  }

  public static string GenarateUrlHome(string strPageName)
  {
    return  (strPageName + ".aspx");
  }

  public static string GenarateUrlHome(string id, string strPrefix, string strName)
  {
      return id + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static string GenarateUrlHomes(string id, string strName)
  {
      return id + "/" + toUrlFriendly(strName) + ".aspx";
  }

  public static string GenarateUrlCateProd(string strId, string strPage, string strPrefix, string strName)
  {
     return strId + "/" + strPage + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";
  }

  public static string GenarateUrlProduct(string strId,string strPrefix,string strName)
  {
      return strId + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";   
  }
  public static string GenarateUrlShopCart(string strLang, string prefix)
  {
    return strLang + "/" + prefix + ".aspx";
  }
  public static string GenarateUrlShopCart(string strLang, string prefix, string strName)
  {
    return strLang + "/" + prefix + "/" + strName + ".aspx";
  }

  public static string GenarateUrlNews(string strId, string prefix, string strName)
  {
      return strId + "/" + prefix + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static string GenarateUrlNewsCate(string strId, string strPage, string prefix, string strName)
  {
      return strId + "/" + strPage + "/" + prefix + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static string GenarateUrlBuyProduct(string strLang,string strPrefix, string strId)
  {
      return strLang + "/" + strId +"/" + strPrefix + ".aspx";
  }

  public static bool SendMail(string fromAddress, string fromPassWord, string fromDisplayName, string toAddress, string subject, string body)
  {
      //--Tạo mail -----------------------------------------------------|
      MailMessage msg = new MailMessage();
      msg.To.Add(toAddress);
      msg.From = new MailAddress(fromAddress, fromDisplayName,
          System.Text.Encoding.UTF8);
      msg.Subject = subject;
      msg.SubjectEncoding = System.Text.Encoding.UTF8;
      msg.Body = body;
      msg.BodyEncoding = System.Text.Encoding.UTF8;
      //--Cho phép gửi mã HTML trong mail ------------------------------|
      msg.IsBodyHtml = true;
      //--Độ ưu tiên của mail ------------------------------------------|
      msg.Priority = MailPriority.High;
      //--Chứng thực bao gồm username + password -----------------------|
      SmtpClient client = new SmtpClient();
      client.Credentials = new System.Net.NetworkCredential
      (fromAddress, fromPassWord);
      //--Cổng 587 của server SMTP Google để gửi mail-------------------|
      client.Port = 587;
      //--Địa chỉ server SMTP của google -------------------------------|
      client.Host = "smtp.gmail.com";
      //--Sử dụng mã hóa đường truyền SSL (Secure Sockets Layer)--------|
      client.EnableSsl = true;
      //--Bắt đầu quá trình gửi mail -----------------------------------|
      try { client.Send(msg); } //--Gửi mail--| 
      catch { return false; } //--Không thể gửi mail     
      return true; //--Gửi mail thành công
  }


  internal static string GetYouTubeScript(string VideoURL, int p, int p_2)
  {
      throw new NotImplementedException();
  }
}